package com.market.utils;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.market.common.Constants;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: hw
 * Date: 13-1-9
 * Time: 上午9:25
 * httpClient get和post 请求公用类
 */
public class HttpClientUtils {

	public static String doGet(String url, String param){
		if(StringUtils.isBlank(url))
			return "404";
		if(StringUtils.isNotBlank(param))
			url += "?" + param;
		String backValue = "";
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		try {
			HttpResponse response = httpClient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			backValue = EntityUtils.toString(entity);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return backValue;
	}

	public static String doPost(String url, Map<String,String> params){
		if(StringUtils.isBlank(url))
			return "404";
		String backValue;
		try {
			UrlEncodedFormEntity entity=null;
			if (params != null) {
				List<NameValuePair> nvs=new ArrayList<>();
				for (Map.Entry<String, String> pair : params.entrySet()) {
					nvs.add(new BasicNameValuePair(pair.getKey(),pair.getValue()));
				}
				entity=new UrlEncodedFormEntity(nvs,"utf-8");
			}
			HttpClient client = new DefaultHttpClient();
			HttpPost postMethod=new HttpPost(url);
			if (entity !=null) {
				postMethod.setEntity(entity);
			}
			HttpResponse response = client.execute(postMethod);
			HttpEntity data = response.getEntity();
			backValue = EntityUtils.toString(data);
		} catch (Throwable e) {
			backValue=e.toString();
		}
		return backValue;
	}

	public static void main(String[] args) {
		Map<String,String> a = new HashMap<>();
		a.put("symbol","TJXAG");
		String s = doPost("http://58.211.8.236:8080/MacBookWebServer/SnapshotResource", a);
		System.out.println(s);
	}
}
